package com.itheima.test6;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class StoreImge implements Runnable {
    private Socket accept;

    public StoreImge(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        BufferedWriter writer = null;
        try {

            bos = new BufferedOutputStream(new FileOutputStream("day16\\copy\\"+ UUID.randomUUID() +".jpg"));
            //建立连接 获取 Socket 对象
            //获取输入流
            InputStream is = accept.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            //边读编写
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {

                bos.write(bytes, 0, len);
            }
            bos.flush();
            // 给客户端写一个响应
            String s = "上传成功";
            OutputStream os = accept.getOutputStream();
            writer = new BufferedWriter(new OutputStreamWriter(os));
            writer.write(s);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer!=null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos!=null) {
                //释放资源
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
